#include <iostream>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>

using namespace std;

int abc;
sem_t sem;

void* Run(void* agd)
{
  char* arr=(char*)agd;
  while(true){
  sleep(1);
  sem_wait(&sem);
  cout<<arr<<' '<<abc<<endl;
  sem_post(&sem);
  }
}

void* Run1(void* agd)
{
  char* arr=(char*)agd;
  while(true)
  {
    sleep(1);
    sem_wait(&sem);
    cout<<arr<<' '<<++abc<<endl;
    sem_post(&sem);
  }
}
int main()
{
  sem_init(&sem,0,1);

  pthread_t se1,se2,se3,se4;
  pthread_create(&se1,nullptr,Run1,(void*)"nihao 1");
  pthread_create(&se2,nullptr,Run,(void*)"nihao 2");
  pthread_create(&se3,nullptr,Run,(void*)"nihao 3");
  pthread_create(&se4,nullptr,Run,(void*)"nihao 4");


  pthread_join(se1,nullptr);
  pthread_join(se2,nullptr);
  pthread_join(se3,nullptr);
  pthread_join(se4,nullptr);

  pthread_cancel(se1);
  pthread_cancel(se2);
  pthread_cancel(se3);
  pthread_cancel(se4);
  sem_destroy(&sem);
  return 0;
}

